import { defineStore } from 'pinia';
// import { cloneDeep } from 'lodash-es';
import { ProjectGroupType, ProjectGroup } from '/@/utils/datav/project';
import * as api from '/@/api/datav/project';

export interface IProjectState {
  allGroups: ProjectGroup[];
}

export const useProjectStore = defineStore('project', {
  state: (): IProjectState => ({
    allGroups: [],
  }),
  getters: {
    group(state) {
      const list = state.allGroups.flatMap((m) => m.children);
      return new ProjectGroup(-1, '全部应用', list);
    },
    unGroup(state) {
      const g = state.allGroups.find((m) => m.type === ProjectGroupType.unGroup);
      return g ? g : new ProjectGroup(0, '未分组', []);
    },
    groups(state) {
      return state.allGroups.filter((m) => m.type === ProjectGroupType.group);
    },
  },
  actions: {
    async getProjects() {
      try {
        const res = await api.getProjects();
        const list: ProjectGroup[] = res || [];
        const unGroup = new ProjectGroup(0, '未分组', []);
        list.forEach((item) => {
          item.children.forEach((subitem) => {
            if (item.type === ProjectGroupType.unGroup) {
              subitem.groupId = 0;
              unGroup.children.push(subitem);
            } else {
              subitem.groupId = item.id;
            }
          });
        });
        this.allGroups = [unGroup, ...list.filter((m) => m.type === ProjectGroupType.group)];
      } catch (error) {
        throw error;
      }
    },
    // async deleteProject(pid: number, gid: number) {
    //   try {
    //     const res = await api.deleteProject(pid);
    //     if (res.data.code === 0) {
    //       const g = this.allGroups.find((m) => m.id === gid);
    //       if (g) {
    //         g.children = g.children.filter((m) => m.id !== pid);
    //       }
    //     } else {
    //       throw Error(res.data.message);
    //     }
    //   } catch (error) {
    //     throw error;
    //   }
    // },
    // async updateProjectName(id: number, newName: string) {
    //   try {
    //     const res = await api.updateProjectName(id, newName);
    //     if (res.data.code !== 0) {
    //       throw Error(res.data.message);
    //     }
    //   } catch (error) {
    //     throw error;
    //   }
    // },
    async moveProject(pid: number, fromId: number, toId: number) {
      try {
        const formG = this.allGroups.find((m) => m.id === fromId);
        const toG = this.allGroups.find((m) => m.id === toId);
        if (formG && toG) {
          const idx = formG.children.findIndex((m) => m.id === pid);
          const p = formG.children.splice(idx, 1)[0];
          p.groupId = toId;
          toG.children.push(p);
        }
      } catch (error) {
        throw error;
      }
    },
    // async copyProject(pid: number, gid: number) {
    //   try {
    //     const res = await api.copyProject(pid);
    //     if (res.data.code === 0) {
    //       const g = this.allGroups.find((m) => m.id === gid);
    //       if (g) {
    //         // TODO: 这里只是简单 cloneDeep，实际应该在后端完成
    //         const p = g.children.find((m) => m.id === pid);
    //         const copy_p = cloneDeep(p);
    //         copy_p.id = Math.round(Math.random() * 1000);
    //         copy_p.name += '_copy';
    //         g.children.push(copy_p);
    //       }
    //     } else {
    //       throw Error(res.data.message);
    //     }
    //   } catch (error) {
    //     throw error;
    //   }
    // },
    /**
     * 创建项目分类
     * @param name
     */
    async createProjectGroup(name: string) {
      try {
        const data = await api.createProjectGroup({ name });
        const newGroup = new ProjectGroup(data, name, []);
        newGroup.type = ProjectGroupType.group;
        this.allGroups.unshift(newGroup);
      } catch (error) {
        throw error;
      }
    },
    /**
     * 删除项目分类
     * @param id
     */
    async deleteProjectGroup(id: number) {
      try {
        await api.deleteProjectGroup();
        const idx = this.allGroups.findIndex((m) => m.id === id);
        const unGroup = this.allGroups.find((m) => m.type === ProjectGroupType.unGroup);
        if (idx > -1 && unGroup) {
          const [group] = this.allGroups.splice(idx, 1);
          group.children.forEach((item) => {
            item.groupId = unGroup.id;
            unGroup.children.push(item);
          });
        }
      } catch (error) {
        throw error;
      }
    },
  },
});
